<?php
defined('BASEPATH') or exit('No direct script access allowed');

class Login extends MY_Controller
{

    public function __construct()
    {
        parent::__construct();
        $this->load->model('User');
        $this->load->model('UserCache');
        $this->load->model('UserPermission');
        $this->load->model('Permission');
        $this->load->helper('get_ip');
    }

    /* 显示登录界面 */
    public function index()
    {
        $this->load->helper('form');
        $this->load->view('admin/login');
    }

    /* 登录操作 */
    public function loginOpt()
    {
        $data = array();
        $this->load->helper('form_check');
        $config = $this->setLoginRules();
        $check = formCheck($config);
        if ($check !== true) {
            $data['loginMessage'] = current($check);
            $this->load->view('admin/login', $data);
            return false;
        }
        $username = $this->input->post('username');
        $password = $this->input->post('password');
        $param = array(
            'username' => $username,
            'password' => $password
        );
        $loginOpt = $this->config->item('wayOfLogin');
        switch ($loginOpt) {
            case 1:
                // 固定密码登录
                $result = $this->loginByFixedPassword($param);
                break;
            case 2:
                // 邮箱登录
                $result = $this->loginByHexinEmail($param);
                break;
            default:
                break;
        }
        if (! $result['code']) {
            $data['loginMessage'] = $result['data'];
            $this->load->view('admin/login', $data);
            return false;
        }
        unset($result['data']['password']);
        $this->setSession($result['data']);
        redirect('home');
    }

    /* 退出登录 */
    public function logout()
    {
        $this->session->sess_destroy();
        redirect('login');
    }

    /* 同花顺邮箱下发密码 */
    public function sendEmailPassword()
    {
        $res = array(
            'code' => 0,
            'msg' => ''
        );
        $this->load->helper('password_by_email');
        $username = trim($_REQUEST['username']);
        $condition = array(
            'username' => $username
        );
        $result = $this->User->find($condition);
        if (empty($result)) {
            $res['msg'] = '账号错误！';
            echo json_encode($res);
            return false;
        }
        $user = $result[0];
        $param = array(
            'type' => 1,
            'username' => $user['email']
        );
        $result = passwordByEmail($param);
        if ($result) {
            $res['code'] = 1;
            $res['msg'] = '发送密码成功！';
        } else {
            $res['msg'] = '发送密码失败！';
        }
        echo json_encode($res);
    }

    /* 固定密码登录 */
    private function loginByFixedPassword($param)
    {
        $result = array();
        $username = $param['username'];
        $password = md5(md5($param['password']));
        $condition = array(
            'username' => $username
        );
        $user = $this->User->find($condition);
        if (empty($user)) {
            $error = '账号不存在！';
        } elseif ($user[0]['password'] != $password) {
            $error = '密码错误！';
        }
        if (isset($error)) {
            $result['code'] = 0;
            $result['data'] = $error;
            return $result;
        }
        
        $result['code'] = 1;
        $result['data'] = $user[0];
        return $result;
    }

    /* 同花顺邮箱登录方式 */
    private function loginByHexinEmail($param)
    {
        $this->load->helper('password_by_email');
        $condition = array(
            'username' => $param['username']
        );
        $result = $this->User->find($condition);
        if (empty($result)) {
            $res = array(
                'code' => 0,
                'data' => '账号错误!'
            );
            return $res;
        }
        $user = $result[0];
        $param['username'] = $user['email'];
        $param['type'] = 2; // 表示验证密码
        $result = passwordByEmail($param);
        if ($result) {
            $res = array(
                'code' => 1,
                'data' => $user
            );
        } else {
            $res = array(
                'code' => 0,
                'data' => '密码错误！'
            );
        }
        return $res;
    }

    /* 设置登录表单验证规则 */
    private function setLoginRules()
    {
        $config = array(
            array(
                'field' => 'username',
                'label' => '用户名',
                'rules' => 'trim|required',
                'errors' => array(
                    'required' => '用户名不能为空！'
                )
            ),
            array(
                'field' => 'password',
                'label' => '密码',
                'rules' => 'trim|required',
                'errors' => array(
                    'required' => '密码不能为空！'
                )
            )
        );
        return $config;
    }

    /* 登录成功后设置session我记录操作 */
    private function setSession($user)
    {
        $ip = getIP();
        $time = time();
        $cache = array(
            'lastLoginIp' => '',
            'lastLoginTime' => '',
            'loginIp' => $ip,
            'loginTime' => date('Y-m-d H:i:s', $time)
        );
        /* user */
        $this->session->set_userdata('user', $user);
        /* cache */
        $userId = $user['id'];
        $condition = array(
            'user_id' => $userId
        );
        $result = $this->UserCache->find($condition);
        $value = array(
            'last_login_ip' => $ip,
            'last_login_time' => $time
        );
        $cache['lastLoginIp'] = $result[0]['last_login_ip'];
        $cache['lastLoginTime'] = date('Y-m-d H:i:s', $result[0]['last_login_time']);
        $result = $this->UserCache->update($condition, $value);
        $this->session->set_userdata('cache', $cache);
        /* permission */
        $result = $this->UserPermission->find($condition);
        $permission = $result[0];
        $this->session->set_userdata('permission', $permission);
        /* permissionCode 这块主要用来控制前端显示的*/
        $condition = array(
            'key' => 'id',
            'value' => explode(',', $permission['permission_id'])
        );
        $field = array(
            'code'
        );
        $result = $this->Permission->findByIn($condition, $field);
        $permissionCode=array();
        foreach($result as $v)
        {
            $permissionCode[] = $v['code'];
        }
        $this->session->set_userdata('permissionCode', $permissionCode);
    }
}